package com.idea.relax.crypto.core;

import com.idea.relax.crypto.config.ICryptoType;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: 沉香
 * @date: 2023/5/11
 * @description:
 */
public class CryptographerRegister implements ICryptographerRegister {

	private final Map<ICryptoType, ICryptographer> cryptographers = new ConcurrentHashMap<>(12);

	@Override
	public void register(ICryptographer cryptographer) {
		Assert.isTrue(cryptographer != null, "ICryptographer不能为空...");
		cryptographers.put(cryptographer.cryptoType(), cryptographer);
	}

	@Override
	public void register(List<ICryptographer> cryptographers) {
		for (ICryptographer cryptographer : cryptographers) {
			register(cryptographer);
		}
	}

	@Override
	public ICryptographer get(ICryptoType cryptoType) {
		return cryptographers.get(cryptoType);
	}

	@Override
	public ICryptographer getIfAbsentThrow(ICryptoType cryptoType) {
		return Optional.ofNullable(cryptographers.get(cryptoType))
			.orElseThrow(() -> new NoSuchElementException("未获取到[" + cryptoType.get() + "]对应的ICryptographer"));
	}

}
